package db

import (
	"log"
	"server/utils"
	"time"
)

const (
	contentTableName = "cache_content"
	kvTableName      = "cache_key_value"
)

// ==单个值，如refresh_token================================================================================================================
func SetCacheContent(content string, maxAge int64) {
	if utils.StrLen(content) > 64 {
		log.Println("content 长度不能超过64个字符", content)
		return
	}
	if !IsTableExist(contentTableName) {
		Exec("create table if not exists cache_content (content varchar(64) not null default '' primary key,exp_time int not null default 0)")
	}
	Exec("delete from cache_content where exp_time<?", time.Now().Unix())

	expTime := time.Now().Add(time.Second * time.Duration(maxAge)).Unix()
	if IsExist(contentTableName, "content=?", content) {
		Exec("update cache_content set exp_time=? where content=?", expTime, content)
	} else {
		Exec("insert into cache_content (content,exp_time) values (?,?)", content, expTime)
	}
}

func IsCacheContentValid(content string) bool {
	if !IsTableExist(contentTableName) {
		return false
	}
	return IsExist(contentTableName, "content=? and exp_time>?", content, time.Now().Unix())
}

func DelCacheContent(content string) {
	if IsTableExist(contentTableName) {
		Exec("delete from cache_content where content=?", content)
	}
}

// ==键值对，如验证码 <clientId，captcha>================================================================================================================

func SetCacheKeyValue(key string, value string, maxAgeSecond int64) {
	if utils.StrLen(key) > 64 {
		log.Println("key 长度不能超过64个字符", key)
		return
	}
	if utils.StrLen(value) > 256 {
		log.Println("value 长度不能超过256个字符")
		return
	}
	if !IsTableExist(kvTableName) {
		Exec("create table if not exists cache_key_value (key_ varchar(64) not null default '' primary key,value varchar(256) not null default '',exp_time int not null default 0)")
	}
	Exec("delete from cache_key_value where exp_time<?", time.Now().Unix())

	expTime := time.Now().Add(time.Second * time.Duration(maxAgeSecond)).Unix()
	if IsExist(kvTableName, "key_=?", key) {
		Exec("update cache_key_value set value=?, exp_time=? where key_=?", value, expTime, key)
	} else {
		Exec("insert into cache_key_value (key_,value,exp_time) values (?,?,?)", key, value, expTime)
	}
}

func GetCacheValue(key string) string {
	if !IsTableExist(kvTableName) {
		return ""
	}
	rows := Select("select * from cache_key_value where key_=? and exp_time>?", key, time.Now().Unix())
	if len(rows) > 0 {
		return rows[0]["value"].(string)
	}
	return ""
}

func IsCacheKeyValid(key string) bool {
	if !IsTableExist(kvTableName) {
		return false
	}
	return IsExist(kvTableName, "key_=? and exp_time>?", key, time.Now().Unix())
}

func DelCacheKey(key string) {
	if IsTableExist(kvTableName) {
		Exec("delete from cache_key_value where key_=?", key)
	}
}
